<template>
  <div style="padding: 50px;">
    <div style="text-align: right;">
      <div style="padding: 10px 0;">
        <el-button type="primary" @click="submit" v-if="viewType !== 'detail'">保存</el-button>
        <el-button @click="()=>{this.$router.back()}">返回列表</el-button>
      </div>
    </div>
    <el-form
      ref="form"
      :rules="rules1"
      label-width="150px"
      label-position="left"
      size="mini"
      :model="data"
      :disabled="viewType === 'detail'"
    >
      <el-form-item label="活动名称：" prop="activityName">
        <el-input
          clearable
          placeholder="请输入活动名称"
          :disabled="viewType === 'edit'"
          v-model="data.activityName"
          style="width: 400px;"
        ></el-input>
      </el-form-item>
      <el-form-item label="领券类型：">
        <el-radio-group v-model="data.collectType">
          <el-radio label="0" :disabled="this.viewType === 'edit'">定向发放</el-radio>
          <el-radio label="1" :disabled="this.viewType === 'edit'">直接领取</el-radio>
          <el-radio label="2" disabled="disabled">活动返券</el-radio>
          <el-radio label="3" disabled="disabled">抽奖</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="有效期：" v-if="data.collectType === '1'" prop="effectDate">
        <div class="effectDateWrapper">
          <el-date-picker
            v-model="data.effectDate"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="viewType === 'add' ? pickerOptions : null"
          ></el-date-picker>
        </div>
      </el-form-item>
      <el-form-item label="活动规则：" v-if="data.collectType === '1'">
        <el-input v-model="data.avtivityRule" :disabled="this.viewType === 'edit'" type="textarea"></el-input>
      </el-form-item>
      <!--领券类型为定向发放时-->
      <div class="couponTypeArea" v-if="data.collectType === '0'">
        <el-form-item label="选择优惠券" style="cursor: pointer;" prop="couponSaveDtoList.batchName">
          <el-input
            placeholder="请选择优惠券"
            readonly="readonly"
            v-model="data.couponSaveDtoList.batchName"
            style="width: 200px; vertical-align: 'middle'; "
          >
            <template slot="append">
              <el-button
                type="text"
                size="small"
                style="padding: 0 10px; color: #409eff;"
                @click="showDirectionCoupon"
              >选择</el-button>
              <input type="hidden" v-model="data.couponSaveDtoList.batchId" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠券发放形式：">
          <el-radio-group v-model="data.grantMethod">
            <el-radio label="1">指定账户</el-radio>
            <el-radio label="2" :disabled="true">指定用户群</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠券剩余数量：">
          <span>{{this.data.couponSaveDtoList.totalNum}}</span>张
        </el-form-item>
        <el-form-item label="单用户发放张数：" prop="couponSaveDtoList.limitNum">
          <el-input
            placeholder="发放张数"
            v-model="data.couponSaveDtoList.limitNum"
            style="width: 400px;"
            clearable
          >
            <template slot="append">
              <span>张</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="发放时间：" prop="grantType">
          <el-radio-group
            v-model="data.grantType"
            :disabled="data.grantType === '1' && viewType === 'edit'"
            style="margin-right: 10px;"
          >
            <el-radio label="1">立即发放</el-radio>
            <el-radio label="2">定时发放</el-radio>
          </el-radio-group>
          <el-date-picker
            v-if="data.grantType === '2'"
            v-model="data.grantTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="是否到账提醒：">
          <el-radio-group v-model="data.arriveType">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否发送短信：">
          <el-radio-group v-model="data.messageType" :disabled="data.arriveType === 0">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否推送AppPush：">
          <el-radio-group
            v-model="data.pushType"
            :disabled="data.arriveType === 0"
            style="margin-right: 10px;"
          >
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
          <el-form-item style="display: inline-block; margin-bottom: 0;">
            <el-input
              clearable
              v-model="data.pushContent"
              :disabled="disabledMessageContent"
              placeholder="请输入AppPush内容"
              style="width: 300px;"
            />
          </el-form-item>
        </el-form-item>
      </div>
      <!--领券类型为直接领取时-->
      <div class="couponTypeArea" v-if="data.collectType === '1'">
        <el-table :data="activityList" border size="small" stripe height="300">
          <el-table-column prop="batchId" label="批次ID" width="100">
            <template slot-scope="{row}">{{row.batchId}}</template>
          </el-table-column>
          <el-table-column prop="batchName" label="券名称" min-width="200">
            <template slot-scope="{$index, row}">
              <el-input
                v-model="row.batchName"
                placeholder="选择优惠券"
                disabled
                style="width: 170px;"
                size="small"
              >
                <template slot="append">
                  <el-button
                    type="text"
                    size="small"
                    style="padding: 0 10px;"
                    @click="showCoupon($index)"
                    :disabled="viewType === 'edit' && row.status === 'fromQuery'"
                  >选择</el-button>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="batchName" label="活动有效期" min-width="270">
            <template slot-scope="{ row }">
              <div class="item-datepicker-wrapper">
                <el-date-picker
                  v-model="row.effectiveStartAndEndTime"
                  size="small"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  :disabled="row.disabled"
                ></el-date-picker>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="batchName" label="每人领券数量" min-width="180">
            <template slot-scope="{row}">
              <!-- <el-input v-model="row.limitNum" placeholder="每人领券数量" size="small" :disabled="row.disabled"/> -->
              <el-input-number
                v-model="row.limitNum"
                controls-position="right"
                size="small"
                :min="0"
                :max="1000000000"
                :disabled="row.disabled"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="batchName" label="活动总数量" min-width="180">
            <template slot-scope="{row}">
              <!-- <el-input v-model="row.totalNum" @input="()=>{
                  row.freeNum = row.totalNum;
              }" placeholder="活动总数量" size="small" :disabled="row.disabled"/>-->
              <el-input-number
                size="small"
                v-model="row.totalNum"
                :disabled="row.disabled"
                controls-position="right"
                @change="onTotalNumChange(row)"
                :min="0"
                :max="1000000000"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="batchName" label="活动剩余库存" min-width="100">
            <template slot-scope="{row}">
              <span>{{row.freeNum}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="batchName" label="操作" align="center" width="150" fixed="right">
            <template slot-scope="{$index, row}">
              <el-button
                v-if="row.disabled"
                type="text"
                size="small"
                @click="editActivity($index)"
              >编辑</el-button>
              <el-button v-else type="text" size="small" @click="save($index)">保存</el-button>
              <el-button
                type="text"
                v-if="viewType !== 'edit'"
                @click="remove($index)"
                size="small"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div
          v-if="viewType !== 'detail'"
          @click="addMore"
          style="height: 50px; background:#f2f2f2; text-align: center; line-height: 50px; cursor: pointer;"
        >
          <span style="font-size: 16px; color: '#999'">新增券</span>
        </div>
      </div>
    </el-form>
    <el-dialog title="优惠券批次选择" :visible.sync="visible" width="65%">
      <el-form
        :inline="true"
        :model="form"
        label-width="70px"
        label-position="left"
        size="mini"
        class="demo-form-inline"
        style="padding-top: 18px;"
        @submit.native.prevent
      >
        <el-form-item label="批次ID">
          <el-input clearable v-model="form.id" placeholder="批次ID" style="width:150px;"></el-input>
        </el-form-item>
        <el-form-item label="批次名称">
          <el-input
            clearable
            v-model="form.batchName"
            placeholder="批次名称"
            class="the-input"
            style="width:150px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="申请人">
          <el-input
            clearable
            v-model="form.applyName"
            placeholder="申请人"
            class="the-input"
            style="width:150px;"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button native-type="submit" type="primary" @click="doSearch(data.collectType)">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="singleTable"
        :data="couponList"
        style="width: 100%"
        border
        size="small"
        height="200"
        highlight-current-row
        @current-change="handleCurrentChange"
        fit
        stripe
      >
        <el-table-column width="100" align="left" label="批次ID" fixed>
          <template slot-scope="{row}">
            <el-radio v-model="currentRowId" :label="row.couponsId" v-if="data.collectType === '0'"></el-radio>
            <el-checkbox
              v-model="row.id"
              :checked="row.check"
              :label="row.couponsId"
              :disabled="isDisabled(row)"
              @change="onCheckboxCheck($event, row)"
              v-else
            />
          </template>
        </el-table-column>
        <!-- <el-table-column prop="couponsId" label="批次ID" width="60"></el-table-column> -->
        <el-table-column prop="batchName" label="批次名称"></el-table-column>
        <el-table-column
          prop="providedType"
          label="发放方式"
          width="100"
          :formatter="providedTypeFormat"
        ></el-table-column>
        <el-table-column prop="stockNum" label="剩余数量"></el-table-column>
        <el-table-column
          prop="startTime"
          :formatter="(row, column, cellValue, index)=>{
            if (row.startTime && row.endTime) {
              return row.startTime + '至' + row.endTime;
            }
            return '';
          }"
          label="有效时间"
        ></el-table-column>
      </el-table>
      <div class="pagination-area" style>
        <el-pagination
          background
          :page-sizes="[100, 200, 300, 400]"
          @size-change="handleCouponListSizeChange"
          @current-change="handleCouponListCurrentChange"
          :page-size="form.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="currentRow = null,currentRowId='',visible = false">取 消</el-button>
        <el-button type="primary" @click="sureSelectCoupon">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { addActivity } from '@/api/coupon/activity'
import {
  getCouponList,
  showActivityDetail,
  queryCouponListByActivity,
  doEditActivity,
} from '@/api/coupon'
import { validate, dateFormat } from '@/utils'

let tableRowIndex = 0;

export default {
  name: "add-activity",
  data() {
    const params = this.$route.query;
    const viewType = params.viewType || "add";

    return {
      id: params.id,
      viewType: viewType,
      rules1: {
        activityName: [
          {
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error("活动名称不能为空!"));
              }
              if (value.length > 50) {
                return callback(new Error("活动名称长度不能超过50以内！"));
              }
              // console.log(validate(value));
              if (
                !/^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z0-9_]){1,50}$/.test(
                  value
                )
              ) {
                return callback(
                  new Error("活动名称只能填写字母、数字或字符串！")
                );
              }
              callback();
            },
          },
        ],
        "couponSaveDtoList.batchName": [
          { required: true, message: "请选择优惠券!", trigger: "change" },
        ],
        "couponSaveDtoList.limitNum": [
          { required: true, message: "请选择优惠券数量!", trigger: "blur" },
        ],
        grantType: [
          { required: true, message: "请选择发放时间!", trigger: "change" },
        ],
        effectDate: [
          { required: true, message: "请选择有效期!", trigger: "change" },
        ],
      },
      rules: {
        costRatio: [
          {
            validator: (rule, value, callback) => {
              if (value === "") {
                callback(new Error("费用比例不能为空！"));
              }
              if (value !== "100") {
                callback(new Error("费用比例必须为100"));
              }

              if (
                this.data.couponsCostDtos.costRatio !== "" &&
                this.data.couponsCostDtos.costRatio === "100"
              ) {
                this.$refs.form.validateField("costRatio");
              }
            },
            trigger: "blur",
          },
        ],
        providedType: [
          { required: true, message: "发放方式不能为空!", trigger: "blur" },
        ],
        couponsCostDtosType: [
          { required: true, message: "费用归属不能为空!", trigger: "blur" },
        ],
        batchName: [
          {
            required: true,
            message: "优惠券批次名称不能为空!",
            trigger: "blur",
          },
        ],
        batchType: [
          {
            required: true,
            message: "优惠券使用类型不能为空!",
            trigger: "blur",
          },
        ],
        batchMoney: [
          { required: true, message: "优惠券金额不能为空!", trigger: "blur" },
        ],
        limitMoney: [
          { required: true, message: "优惠券限额不能为空!", trigger: "blur" },
        ],
        showTitle: [
          { required: true, message: "前端展示标题不能为空!", trigger: "blur" },
        ],
        // 使用场景限制
        sceneType: [
          {
            required: true,
            message: "使用场景限制至少选一个!",
            trigger: "blur",
          },
        ],
        // 使用商户限制
        rangeType: [
          {
            required: true,
            message: "使用场景限制至少选一个!",
            trigger: "blur",
          },
        ],
        timeLimit: [{ required: true, message: "请选择有效期限制类型!" }],
        // 有效期
        effectiveStartAndEndTime: [
          { required: true, message: "请选择有效期限制类型!" },
        ],
        applicateNum: [
          { required: true, message: "申请数量不能为空!", trigger: "blur" },
        ],
      },
      pickerOptions: {
        disabledDate: (time) => {
          const now = new Date();
          now.setDate(now.getDate() - 1);

          return time.getTime() < now.getTime();
        },
      },
      totalCount: 0,
      form: {
        // 优惠券批次id
        id: "",
        // 优惠券批次名称
        batchName: "",
        // 申请人
        applyName: "",
        pageSize: 10,
        pageIndex: 1,
        provider: "",
        state: "",
      },
      currentRowId: "",
      currentRow: null,
      visible: false, // 活动列表弹窗
      couponList: [],
      activityList: [],
      data: {
        // 活动名称
        activityName: "",
        activityRule: "",
        // 发放时间类型  1:立即发放 2:定时发放
        grantType: "1",
        grantTime: "",
        // 领券类型
        collectType: "0",
        // 优惠券发放形式
        grantMethod: "1",
        // 是否到账提醒（0否 1是）
        arriveType: 0,
        // 是否发送短信（0否 1是）
        messageType: "",
        // 是否推送AppPush（0否 1是）
        pushType: "",
        // 推送内容
        pushContent: "",
        couponSaveDtoList: {
          // 优惠券批次名称
          batchName: "",
          // 优惠券批次id
          batchId: "",
          limitNum: 1,
          totalNum: "0",
          couponEndTime: "",
          couponStartTime: "",
        },
        // 有效期
        effectDate: "",
        startTime: "",
        endTime: "",
        avtivityRule: "",
        status: -1,
      },
      readyActivityList: [],
      // 活动编辑行
      editRow: {
        batchId: "",
        batchName: "",
        limitNum: "",
        date: [],
        couponStartTime: "",
        couponEndTime: "",
        totalNum: "",
        sort: "",
      },
    };
  },
  watch: {
    "data.effectDate": {
      handler: function (val) {
        this.data.startTime = val[0] || "";
        this.data.endTime = val[1] || "";
      },
      deep: true,
    },
    "data.collectType": {
      handler: function (val) {
        this.doSearch(val);
      },
      deep: true,
    },
  },
  created() {
    this.doSearch(this.data.collectType);
  },
  computed: {
    effectiveStartAndEndTime() {
      return [new Date(), new Date()];
    },
    disabledMessageContent() {
      return !(
        this.data.arriveType === 1 &&
        (this.data.messageType === 1 || this.data.pushType === 1)
      );
    },
  },
  methods: {
    handleCouponListSizeChange (pageSize) {
      this.form.pageSize = pageSize;
      this.form.pageIndex = 1;
      this.doSearch(this.data.collectType);
    },
    handleCouponListCurrentChange (pageIndex) {
      this.form.pageIndex = pageIndex;
      this.doSearch(this.data.collectType);
    },
    showDirectionCoupon () {
      this.visible = true;
      this.doSearch(this.data.collectType);
    },

    // 用于控制优惠券批次多选情况下 是否允许选择的问题
    isDisabled (row) {
      const length = this.activityList.filter(item=>{
        return item.batchId == row.couponsId
      }).length;
      return length > 0;
    },
    onTotalNumChange(row) {
      // if (this.viewType !== "edit") {
      //   row.freeNum = row.totalNum;
      // }
      row.freeNum = row.totalNum;
    },
    onCheckboxCheck(e, row) {
      // console.log(e, row);
      row.check = e;
    },
    showCoupon(index) {
      this.visible = true;
      // 用于记录当前选择的是哪一行
      tableRowIndex = index;
    },
    addMore() {
      console.log(this.activityList);
      this.activityList.push({
        index: -1,
        batchId: "",
        batchName: "",
        effectiveStartAndEndTime: [],
        limitNum: 0,
        totalNum: 0,
        freeNum: 0,
        disabled: false,
      });
    },
    providedTypeFormat(row, column, cellValue, index) {
      return cellValue === 0 ? "定向发放" : "直接领取";
    },
    doSearch(collectType) {
      // 加载活动列表
      queryCouponListByActivity(this.form.pageIndex, this.form.pageSize, {
        applyName: this.form.applyName,
        batchName: this.form.batchName,
        couponsId: this.form.id,
        providerType: collectType,
      }).then((res) => {
        const { result } = res;
        if (result) {
          this.couponList = result.records.map((item) => {
            item["check"] = false;
            return item;
          });
          this.totalCount = result.total;
        }
      });
    },
    handleCurrentChange(row) {
      // console.log(row);
      if (row) {
        this.currentRowId = row.couponsId;
        this.currentRow = row;
        this.$refs.singleTable.setCurrentRow(row);
      }
    },
    // 选中优惠券
    sureSelectCoupon() {
      if (this.data.collectType !== "1") {
        this.data.couponSaveDtoList.batchId = this.currentRow.couponsId;
        this.data.couponSaveDtoList.batchName = this.currentRow.batchName;
        this.data.couponSaveDtoList.totalNum = this.currentRow.stockNum;
      } else {
        this.editRow.batchId = this.currentRow.id;
        this.editRow.batchName = this.currentRow.batchName;

        // 用于判断activityList中是否已经涵盖相同的优惠券批次ID
        const isTrue = (batchId) => {
          return (
            this.activityList.filter((item) => {
              return item.batchId === batchId;
            }).length > 0
          );
        };

        // 20200811
        // 与许云飞沟通过滤已经选择过的优惠券
        const checkedItems = this.couponList
          .filter((item) => item.check)
          .filter((item) => {
            const res = isTrue(item.couponsId);
            return !res;
          });

        const index = 0;

        if (checkedItems.length > 0) {
          this.activityList[tableRowIndex].batchId = checkedItems[0].couponsId;
          this.activityList[tableRowIndex].batchName =
            checkedItems[0].batchName;

          for (let i = 1; i <= checkedItems.length - 1; i++) {
            this.activityList.push({
              index: -1,
              batchId: checkedItems[i].couponsId,
              batchName: checkedItems[i].batchName,
              effectiveStartAndEndTime: [],
              limitNum: 0,
              totalNum: 0,
              freeNum: 0,
              disabled: false,
            });
          }
        }
      }

      this.visible = false;
    },
    // 定向发放
    async submit() {
      try {
        await this.$refs.form.validate();
        if (this.data.collectType === "0") {
          if (this.viewType === "add") {
            const res = await addActivity(
              Object.assign(
                { ...this.data },
                {
                  couponSaveDtoList: [
                    {
                      ...this.data.couponSaveDtoList,
                      couponEndTime: this.currentRow.couponEndTime || "",
                      couponStartTime: this.currentRow.couponStartTime || "",
                    },
                  ],
                }
              )
            );
            if (res.code === 200) {
              this.$message.success("操作成功！");
              this.$router.back();
            } else {
              this.$message.error(res.message);
            }
          } else if (this.viewType === "edit") {
            console.log(this.currentRow);
            const res = await doEditActivity(
              this.id,
              Object.assign(
                { ...this.data },
                {
                  couponSaveDtoList: [
                    {
                      ...this.data.couponSaveDtoList,
                      // couponEndTime: this.currentRow.couponEndTime || "",
                      // couponStartTime: this.currentRow.couponStartTime || "",
                    },
                  ],
                }
              )
            );
            if (res.code === 200) {
              this.$message.success("操作成功！");
              this.$router.back();
            } else {
              this.$message.error(res.message);
            }
          }
        } else {
          const { activityName, collectType, startTime, endTime } = this.data;
          // 过滤出disabled为true的数据
          // disabled为true 说明用户点了保存
          const couponSaveDtoList = this.activityList
            .filter((v) => v.disabled)
            .map((item) => {
              return {
                batchId: item.batchId,
                couponStartTime: item.effectiveStartAndEndTime[0],
                couponEndTime: item.effectiveStartAndEndTime[1],
                limitNum: item.limitNum,
                totalNum: item.totalNum,
              };
            });

          if (couponSaveDtoList.length === 0) {
            this.$message("请配置新增券，配置完毕后请点击保存！");
            return;
          }

          const params = {
            activityName,
            collectType,
            startTime,
            endTime,
            couponSaveDtoList,
          };

          if (this.viewType === "add") {
            const res = await addActivity(params);
            if (res.code === 200) {
              this.$message.success("操作成功！");
              this.$router.back();
            } else {
              this.$message.error(res.message);
            }
          } else {
            const res = await doEditActivity(this.id, params);
            if (res.code === 200) {
              this.$message.success("操作成功！");
              this.$router.back();
            } else {
              this.$message.error(res.message);
            }
          }
        }
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    // 数据表格-保存
    save(i) {
      const currentRow = this.activityList[i];
      console.log(currentRow);
      if (currentRow.effectiveStartAndEndTime.length === 0) {
        this.$message.error("活动有效期不能为空!");
        return;
      }

      if (currentRow.effectiveStartAndEndTime.length < 2) {
        this.$message.error("请选择完整的有效期时间!");
        return;
      }

      if (
        currentRow.effectiveStartAndEndTime[0] ===
        currentRow.effectiveStartAndEndTime[1]
      ) {
        this.$message.error("开始时间结束时间不能相同!");
        return;
      }

      // const now = new Date();
      // if (new Date(currentRow.effectiveStartAndEndTime[0].replace(/-/g, '/')) < now) {
      //   this.$message.error('开始时间不能小于当前时间!');
      //   return;
      // }

      const now = new Date(dateFormat(new Date(), "yyyy/MM/dd"));
      if (
        new Date(currentRow.effectiveStartAndEndTime[0].replace(/-/g, "/")) <
        now
      ) {
        this.$message.error("开始时间不能小于当前时间!");
        return;
      }

      if (!isNaN(currentRow.limitNum) && currentRow.limitNum === 0) {
        this.$message.error("每人领券数量不能为0");
        return;
      }

      if (!isNaN(currentRow.totalNum) && currentRow.totalNum === 0) {
        this.$message.error("活动总数量不能为0");
        return;
      }

      currentRow.disabled = true;
    },
    // 数据表格-移除
    remove(i) {
      this.$confirm("确定要删除该数据吗？", "删除确认", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {this.activityList.splice(i, 1);}).catch(e=>console.log(e));
    },
    // 数据表格-编辑
    editActivity(i) {
      this.activityList[i].disabled = false;
      // this.activityList[i].edit = true;
    },
  },
  created () {
    if (this.viewType === "detail" || this.viewType === "edit") {
      showActivityDetail(this.id).then((res) => {
        if (res.code === 200) {
          const result = res.result;
          console.log(result);
          this.data.activityName = result.activityName;
          if (result.collectType === 0) {
            this.data.arriveType = result.arriveType;
            // this.data.arriveType = this.data.arriveType;
            this.data.grantMethod = result.grantMethod.toString();
            this.data.grantType = result.grantType.toString();
            this.data.pushType = result.pushType;
            this.data.messageType = result.messageType;
            /*
            // 优惠券批次名称
              batchName: "",
              // 优惠券批次id
              batchId: "",
              limitNum: 1,
              totalNum: "0",
            */
            this.data.couponSaveDtoList.batchName =
              result.couponDetailVos[0].batchName;
            this.data.couponSaveDtoList.batchId =
              result.couponDetailVos[0].batchId;
            this.data.couponSaveDtoList.limitNum =
              result.couponDetailVos[0].limitNum;
            this.data.couponSaveDtoList.totalNum =
              result.couponDetailVos[0].totalNum;
            this.data.couponSaveDtoList.couponEndTime =
              result.couponDetailVos[0].endTime;
            this.data.couponSaveDtoList.couponStartTime =
              result.couponDetailVos[0].startTime;
          } else {
            this.data.arriveType = "";
            // this.data.arriveType = "";
            this.data.grantMethod = "";
            this.data.grantType = "";
            this.data.pushType = "";
            this.data.messageType = "";
            // 直接领取-活动列表
            this.activityList = result.couponDetailVos.map((item) => {
              return {
                disabled: true,
                index: -1,
                batchId: item.batchId,
                batchName: item.batchName,
                effectiveStartAndEndTime: [item.startTime, item.endTime],
                limitNum: item.limitNum,
                totalNum: item.totalNum,
                freeNum: item.surplusNum,
                status: 'fromQuery',
              };
            });
          }

          this.data.avtivityRule = result.avtivityRule;
          this.data.collectType = result.collectType.toString();
          this.data.startTime = result.startTime;
          this.data.endTime = result.endTime;
          // this.data.grantMethod = result.grantMethod
          //   ? result.grantMethod.toString()
          //   : "";
          this.data.grantTime = result.grantTime;

          this.data.id = result.id;
          this.data.pushContent = result.pushContent;

          this.data.status = result.status;
          this.data.effectDate = [result.startTime, result.endTime];
          // this.data.effectiveStartAndEndTime = [result.startTime, result.endTime];
        } else {
          this.$message.error(res.message);
        }
      });
    }
  },
  mounted() {
    // if (this.viewType === "detail" || this.viewType === "edit") {
    //   showActivityDetail(this.id).then((res) => {
    //     if (res.code === 200) {
    //       const result = res.result;
    //       console.log(result);
    //       this.data.activityName = result.activityName;
    //       if (result.collectType === 0) {
    //         // this.data.arriveType = result.arriveType.toString();
    //         this.data.arriveType = this.data.arriveType;
    //         this.data.grantMethod = result.grantMethod.toString();
    //         this.data.grantType = result.grantType.toString();
    //         this.data.pushType = result.pushType;
    //         this.data.messageType = result.messageType;
    //         /*
    //         // 优惠券批次名称
    //           batchName: "",
    //           // 优惠券批次id
    //           batchId: "",
    //           limitNum: 1,
    //           totalNum: "0",
    //         */
    //         this.data.couponSaveDtoList.batchName =
    //           result.couponDetailVos[0].batchName;
    //         this.data.couponSaveDtoList.batchId =
    //           result.couponDetailVos[0].batchId;
    //         this.data.couponSaveDtoList.limitNum =
    //           result.couponDetailVos[0].limitNum;
    //         this.data.couponSaveDtoList.totalNum =
    //           result.couponDetailVos[0].totalNum;
    //         this.data.couponSaveDtoList.couponEndTime =
    //           result.couponDetailVos[0].endTime;
    //         this.data.couponSaveDtoList.couponStartTime =
    //           result.couponDetailVos[0].startTime;
    //       } else {
    //         this.data.arriveType = "";
    //         this.data.arriveType = "";
    //         this.data.grantMethod = "";
    //         this.data.grantType = "";
    //         this.data.pushType = "";
    //         this.data.messageType = "";
    //         // 直接领取-活动列表
    //         this.activityList = result.couponDetailVos.map((item) => {
    //           return {
    //             disabled: true,
    //             index: -1,
    //             batchId: item.batchId,
    //             batchName: item.batchName,
    //             effectiveStartAndEndTime: [item.startTime, item.endTime],
    //             limitNum: item.limitNum,
    //             totalNum: item.totalNum,
    //             freeNum: item.surplusNum,
    //             status: 'fromQuery',
    //           };
    //         });
    //       }

    //       this.data.avtivityRule = result.avtivityRule;
    //       this.data.collectType = result.collectType.toString();
    //       this.data.startTime = result.startTime;
    //       this.data.endTime = result.endTime;
    //       // this.data.grantMethod = result.grantMethod
    //       //   ? result.grantMethod.toString()
    //       //   : "";
    //       this.data.grantTime = result.grantTime;

    //       this.data.id = result.id;
    //       this.data.pushContent = result.pushContent;

    //       this.data.status = result.status;
    //       this.data.effectDate = [result.startTime, result.endTime];
    //       // this.data.effectiveStartAndEndTime = [result.startTime, result.endTime];
    //     } else {
    //       this.$message.error(res.message);
    //     }
    //   });
    // }
  },
};
</script>

<style lang="scss">
.addconfig-input {
  width: 340px;
}
.effectiveStartAndEndTime {
  .el-date-editor {
    width: 340px !important;
  }
}
.effectDateWrapper {
  .el-date-editor {
    width: 400px !important;
  }
}
.item-datepicker-wrapper {
  .el-date-editor {
    width: 250px !important;
  }
}
.couponTypeArea {
  border: 1px solid #ddd;
  padding: 10px;
}
</style>